import React, { useState } from 'react';
import { 
  Card, 
  Upload, 
  Button, 
  Form, 
  Input, 
  Select, 
  InputNumber, 
  message, 
  Steps, 
  Alert, 
  Spin,
  Space,
  Typography,
  Divider,
  DatePicker,
  Table,
  Tag,
  Row,
  Col,
  Modal
} from 'antd';
import { 
  InboxOutlined, 
  FileTextOutlined, 
  RobotOutlined, 
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CalendarOutlined,
  ReloadOutlined,
  UploadOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { 
  FileUploadResult, 
  ScheduleGenerationRequest, 
  ScheduleGenerationResponse,
  AIAnalysisResult 
} from '../types/schedule';
import { scheduleService } from '../services/scheduleService';

const { Dragger } = Upload;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;
const { Step } = Steps;

interface ScheduleUploadProps {
  onAnalysisComplete: (result: AIAnalysisResult) => void;
  onError: (error: string) => void;
}

const ScheduleUpload: React.FC<ScheduleUploadProps> = ({ 
  onAnalysisComplete, 
  onError 
}) => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [uploading, setUploading] = useState(false);
  const [analyzing, setAnalyzing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [uploadResult, setUploadResult] = useState<FileUploadResult | null>(null);
  const [analysisResult, setAnalysisResult] = useState<AIAnalysisResult | null>(null);
  const [chatInput, setChatInput] = useState('');
  const [chatMessages, setChatMessages] = useState<Array<{type: 'user' | 'ai', content: string}>>([]);

  // 文件上传处理
  const handleUpload = async (file: File) => {
    try {
      setUploading(true);
      
      // 检查文件类型
      const allowedTypes = [
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
        'application/vnd.ms-excel', // .xls
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
        'application/msword' // .doc
      ];
      
      if (!allowedTypes.includes(file.type)) {
        message.error('只支持 PDF、Excel、Word 格式的文件！');
        return false;
      }
      
      // 检查文件大小 (10MB)
      if (file.size > 10 * 1024 * 1024) {
        message.error('文件大小不能超过 10MB！');
        return false;
      }

      // 调用实际的上传API
      console.log('开始上传文件:', file.name);
      const response = await scheduleService.uploadFile(file);
      console.log('文件上传响应:', response);
      
      // 由于api拦截器返回的是response.data，所以response就是后端返回的整个对象
      // 后端返回: { success: true, message: '...', data: {...} }
      if (!response.success) {
        throw new Error(response.message || '文件上传失败');
      }
      
      // 创建一个符合FileUploadResult接口的对象
      const uploadResult: FileUploadResult = {
        success: response.success,
        message: response.message,
        data: response.data
      };
      
      setUploadResult(uploadResult);
      setCurrentStep(1);
      message.success('文件上传成功！');
      
      return false; // 阻止默认上传行为
    } catch (error) {
      console.error('文件上传失败:', error);
      message.error('文件上传失败，请重试');
      onError('文件上传失败');
      return false;
    } finally {
      setUploading(false);
    }
  };

  // AI分析处理
  const handleAnalysis = async () => {
    try {
      setAnalyzing(true);
      
      if (!uploadResult?.data) {
        message.error('请先上传文件');
        return;
      }

      const request: ScheduleGenerationRequest = {
        fileId: uploadResult.data.uploadId,
        startWeek: 1, // 默认从第1周开始，AI会自动分析
        semester: '', // AI会自动从表格中提取
        totalWeeks: 0, // AI会自动从表格中提取
        startDate: '' // AI会自动从表格中提取
      };

      console.log('开始AI智能分析，请求参数:', request);
      
      // 调用实际的AI分析API
      const response = await scheduleService.generateSchedule(request);
      console.log('AI分析API响应:', response);
      
      // 由于API拦截器已经返回了response.data，所以response就是后端返回的整个对象
      // 后端返回: { success: true, message: '...', data: {...} }
      if (!response.success) {
        throw new Error(response.message || 'AI分析失败');
      }
      
      const analysisResult = response.data;
      console.log('AI分析结果:', analysisResult);
      
      if (analysisResult) {
        setAnalysisResult(analysisResult);
        setCurrentStep(2);
        message.success('AI智能分析完成！');
      } else {
        throw new Error('AI分析结果为空');
      }
      
    } catch (error) {
      console.error('AI分析失败:', error);
      message.error('AI分析失败，请重试');
      onError('AI分析失败');
    } finally {
      setAnalyzing(false);
    }
  };

  // 确认分析结果
  const handleConfirm = async () => {
    if (analysisResult) {
      setSaving(true);
      try {
        await onAnalysisComplete(analysisResult);
        // 成功后重置状态
        setCurrentStep(0);
        setAnalysisResult(null);
        setUploadResult(null);
        form.resetFields();
      } catch (error) {
        console.error('保存课表失败:', error);
      } finally {
        setSaving(false);
      }
    }
  };

  // 重新分析
  const handleRetry = () => {
    setCurrentStep(1);
    setAnalysisResult(null);
  };

  // AI聊天处理
  const handleChatSend = async () => {
    if (!chatInput.trim()) return;
    
    const userMessage = chatInput.trim();
    setChatInput('');
    
    // 添加用户消息
    setChatMessages(prev => [...prev, { type: 'user', content: userMessage }]);
    
    try {
      // 这里可以调用AI聊天API，暂时模拟AI回复
      const aiResponse = `我理解您的问题："${userMessage}"。关于课表信息，我可以帮您：
1. 修改课程信息
2. 添加或删除课程
3. 调整时间安排
4. 解释课程详情

请告诉我您具体需要什么帮助？`;
      
      // 添加AI回复
      setTimeout(() => {
        setChatMessages(prev => [...prev, { type: 'ai', content: aiResponse }]);
      }, 1000);
      
    } catch (error) {
      console.error('AI聊天失败:', error);
      setChatMessages(prev => [...prev, { 
        type: 'ai', 
        content: '抱歉，AI助手暂时无法回复，请稍后再试。' 
      }]);
    }
  };

  const steps = [
    {
      title: '上传文件',
      description: '上传课表文档',
      icon: <InboxOutlined />
    },
    {
      title: 'AI分析',
      description: 'AI智能解析',
      icon: <RobotOutlined />
    },
    {
      title: '确认结果',
      description: '确认课表信息',
      icon: <CheckCircleOutlined />
    }
  ];

  return (
    <Card>
      <Title level={4}>
        <FileTextOutlined style={{ marginRight: '8px' }} />
        课表上传与AI分析
      </Title>
      
      <Steps current={currentStep} style={{ marginBottom: '24px' }}>
        {steps.map((step, index) => (
          <Step 
            key={index} 
            title={step.title} 
            description={step.description}
            icon={step.icon}
          />
        ))}
      </Steps>

      {/* 步骤1: 文件上传 */}
      {currentStep === 0 && (
        <div>
          <Paragraph>
            请上传包含课表信息的文档，支持 PDF、Excel、Word 格式。
            AI将自动解析文档中的课程信息。
          </Paragraph>
          
          <Dragger
            name="file"
            multiple={false}
            beforeUpload={handleUpload}
            showUploadList={false}
            disabled={uploading}
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">
              {uploading ? '上传中...' : '点击或拖拽文件到此区域上传'}
            </p>
            <p className="ant-upload-hint">
              支持 PDF、Excel、Word 格式，文件大小不超过 10MB
            </p>
          </Dragger>
          
          {uploading && (
            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <Spin size="large" />
              <div style={{ marginTop: '8px' }}>文件上传中...</div>
            </div>
          )}
        </div>
      )}

      {/* 步骤2: AI智能分析 */}
      {currentStep === 1 && (
        <div>
          {uploadResult && (
            <Alert
              message="文件上传成功"
              description={`文件名: ${uploadResult.data?.fileName} (${(uploadResult.data?.fileSize! / 1024 / 1024).toFixed(2)}MB)`}
              type="success"
              showIcon
              style={{ marginBottom: '16px' }}
            />
          )}
          
          <Alert
            message="AI智能分析"
            description="系统将自动分析Excel表格结构，提取学期信息、课程安排等数据，无需手动输入参数。"
            type="info"
            showIcon
            style={{ marginBottom: '16px' }}
          />
          
          <div style={{ textAlign: 'center', marginBottom: '16px' }}>
            <Button 
              type="primary" 
              onClick={handleAnalysis}
              loading={analyzing}
              size="large"
              icon={<RobotOutlined />}
            >
              {analyzing ? 'AI分析中...' : '开始智能分析'}
            </Button>
          </div>
          
          {analyzing && (
            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <Spin size="large" />
              <div style={{ marginTop: '8px' }}>
                AI正在分析表格结构，提取课程信息...
              </div>
            </div>
          )}
        </div>
      )}

      {/* 步骤3: 确认结果 */}
      {currentStep === 2 && analysisResult && (
        <div>
          {/* AI交流框 */}
          <Card title="AI助手" style={{ marginBottom: '16px' }}>
            <div style={{ height: '200px', border: '1px solid #d9d9d9', borderRadius: '6px', padding: '12px', marginBottom: '12px', overflowY: 'auto' }}>
              <div style={{ marginBottom: '8px' }}>
                <strong>AI:</strong> 我已经分析了您的课表，发现了一些需要确认的信息：
              </div>
              {analysisResult.questions && analysisResult.questions.map((question, index) => (
                <div key={index} style={{ marginBottom: '8px', padding: '8px', backgroundColor: '#f0f0f0', borderRadius: '4px' }}>
                  <strong>问题{index + 1}:</strong> {question}
                </div>
              ))}
              
              {/* 聊天消息 */}
              {chatMessages.map((msg, index) => (
                <div key={index} style={{ marginTop: '8px', padding: '8px', borderRadius: '4px', backgroundColor: msg.type === 'user' ? '#e6f7ff' : '#f6ffed' }}>
                  <strong>{msg.type === 'user' ? '您' : 'AI'}:</strong> {msg.content}
                </div>
              ))}
            </div>
            <Space.Compact style={{ width: '100%' }}>
              <Input
                placeholder="与AI交流..."
                value={chatInput}
                onChange={(e) => setChatInput(e.target.value)}
                onPressEnter={() => handleChatSend()}
              />
              <Button 
                type="primary" 
                onClick={handleChatSend}
                disabled={!chatInput.trim()}
              >
                发送
              </Button>
            </Space.Compact>
          </Card>
          <Alert
            message="AI分析完成"
            description={`成功解析出 ${analysisResult.courses.length} 门课程，置信度: ${(analysisResult.confidence * 100).toFixed(1)}%`}
            type="success"
            showIcon
            style={{ marginBottom: '16px' }}
          />
          
          {/* 学期信息 */}
          {analysisResult.semesterInfo && (
            <Card title="学期信息" style={{ marginBottom: '16px' }}>
              <Row gutter={16}>
                <Col span={6}>
                  <div><strong>学期:</strong> {analysisResult.semesterInfo.semester}</div>
                </Col>
                <Col span={6}>
                  <div><strong>开始日期:</strong> {analysisResult.semesterInfo.startDate}</div>
                </Col>
                <Col span={6}>
                  <div><strong>结束日期:</strong> {analysisResult.semesterInfo.endDate}</div>
                </Col>
                <Col span={6}>
                  <div><strong>总周数:</strong> {analysisResult.semesterInfo.totalWeeks}周</div>
                </Col>
              </Row>
              {analysisResult.semesterInfo.classTimes && (
                <div style={{ marginTop: '12px' }}>
                  <strong>上课时间:</strong>
                  <div style={{ marginTop: '4px' }}>
                    {analysisResult.semesterInfo.classTimes.morning && (
                      <span style={{ marginRight: '16px' }}>上午: {analysisResult.semesterInfo.classTimes.morning}</span>
                    )}
                    {analysisResult.semesterInfo.classTimes.afternoon && (
                      <span style={{ marginRight: '16px' }}>下午: {analysisResult.semesterInfo.classTimes.afternoon}</span>
                    )}
                    {analysisResult.semesterInfo.classTimes.evening && (
                      <span>晚上: {analysisResult.semesterInfo.classTimes.evening}</span>
                    )}
                  </div>
                </div>
              )}
            </Card>
          )}
          
          {/* 表格结构信息 */}
          {analysisResult.tableStructure && (
            <Card title="表格结构分析" style={{ marginBottom: '16px' }}>
              <Row gutter={16}>
                <Col span={6}>
                  <div><strong>星期区域:</strong> {analysisResult.tableStructure.weekArea}</div>
                </Col>
                <Col span={6}>
                  <div><strong>节次区域:</strong> {analysisResult.tableStructure.timeArea}</div>
                </Col>
                <Col span={6}>
                  <div><strong>课程区域:</strong> {analysisResult.tableStructure.courseArea}</div>
                </Col>
                <Col span={6}>
                  <div><strong>备注区域:</strong> {analysisResult.tableStructure.notesArea}</div>
                </Col>
              </Row>
              {analysisResult.tableStructure.timeArea2 && (
                <Row gutter={16} style={{ marginTop: '8px' }}>
                  <Col span={6}>
                    <div><strong>节次区域2:</strong> {analysisResult.tableStructure.timeArea2}</div>
                  </Col>
                </Row>
              )}
            </Card>
          )}
          
          {analysisResult.warnings.length > 0 && (
            <Alert
              message="注意事项"
              description={
                <ul style={{ margin: 0, paddingLeft: '20px' }}>
                  {analysisResult.warnings.map((warning, index) => (
                    <li key={index}>{warning}</li>
                  ))}
                </ul>
              }
              type="warning"
              showIcon
              style={{ marginBottom: '16px' }}
            />
          )}
          
          {analysisResult.suggestions.length > 0 && (
            <Alert
              message="建议"
              description={
                <ul style={{ margin: 0, paddingLeft: '20px' }}>
                  {analysisResult.suggestions.map((suggestion, index) => (
                    <li key={index}>{suggestion}</li>
                  ))}
                </ul>
              }
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
          )}
          
          <Divider />
          
          {/* 课程信息表格 */}
          <Card 
            title="解析的课程信息" 
            style={{ marginBottom: '16px' }}
            extra={
              <Button 
                type="primary" 
                size="small"
                onClick={() => {
                  const newCourse = {
                    id: `course_${Date.now()}`,
                    name: '新课程',
                    teacher: '教师',
                    classroom: '教室',
                    weeks: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],
                    dayOfWeek: 1,
                    timeSlot: 1,
                    duration: 2,
                    credits: 3,
                    type: 'required' as const,
                    description: ''
                  };
                  setAnalysisResult({
                    ...analysisResult,
                    courses: [...analysisResult.courses, newCourse]
                  });
                }}
              >
                添加课程
              </Button>
            }
          >
            <Table
              dataSource={analysisResult.courses.map((course, index) => ({ ...course, key: course.id || index }))}
              columns={[
                {
                  title: '课程名称',
                  dataIndex: 'name',
                  key: 'name',
                  width: 150,
                  render: (text, record, index) => (
                    <Input
                      value={text}
                      onChange={(e) => {
                        const newCourses = [...analysisResult.courses];
                        newCourses[index].name = e.target.value;
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                      size="small"
                    />
                  ),
                },
                {
                  title: '任课教师',
                  dataIndex: 'teacher',
                  key: 'teacher',
                  width: 100,
                  render: (text, record, index) => (
                    <Input
                      value={text}
                      onChange={(e) => {
                        const newCourses = [...analysisResult.courses];
                        newCourses[index].teacher = e.target.value;
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                      size="small"
                    />
                  ),
                },
                {
                  title: '教室',
                  dataIndex: 'classroom',
                  key: 'classroom',
                  width: 100,
                  render: (text, record, index) => (
                    <Input
                      value={text}
                      onChange={(e) => {
                        const newCourses = [...analysisResult.courses];
                        newCourses[index].classroom = e.target.value;
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                      size="small"
                    />
                  ),
                },
                {
                  title: '时间',
                  key: 'time',
                  width: 120,
                  render: (_, record, index) => {
                    const weekDays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                    
                    const getTimeRange = (startSlot: number, duration: number) => {
                      const endSlot = startSlot + duration - 1;
                      if (duration === 1) {
                        return `第${startSlot}节`;
                      } else {
                        return `第${startSlot}-${endSlot}节`;
                      }
                    };
                    
                    return (
                      <div>
                        <div style={{ marginBottom: '4px' }}>
                          <Select
                            value={record.dayOfWeek}
                            onChange={(value) => {
                              const newCourses = [...analysisResult.courses];
                              newCourses[index].dayOfWeek = value;
                              setAnalysisResult({ ...analysisResult, courses: newCourses });
                            }}
                            size="small"
                            style={{ width: '80px' }}
                          >
                            {weekDays.slice(1).map((day, idx) => (
                              <Option key={idx + 1} value={idx + 1}>{day}</Option>
                            ))}
                          </Select>
                        </div>
                        <div>
                          <Input
                            value={record.timeSlot}
                            onChange={(e) => {
                              const newCourses = [...analysisResult.courses];
                              newCourses[index].timeSlot = parseInt(e.target.value) || 1;
                              setAnalysisResult({ ...analysisResult, courses: newCourses });
                            }}
                            size="small"
                            style={{ width: '50px' }}
                            type="number"
                            min="1"
                            max="12"
                            placeholder="节次"
                          />
                        </div>
                        <div style={{ marginTop: '4px' }}>
                          <Input
                            value={record.duration}
                            onChange={(e) => {
                              const newCourses = [...analysisResult.courses];
                              newCourses[index].duration = parseInt(e.target.value) || 1;
                              setAnalysisResult({ ...analysisResult, courses: newCourses });
                            }}
                            size="small"
                            style={{ width: '50px' }}
                            type="number"
                            min="1"
                            max="4"
                            placeholder="持续"
                          />
                        </div>
                        <div style={{ marginTop: '4px', fontSize: '12px', color: '#666', textAlign: 'center' }}>
                          {getTimeRange(record.timeSlot, record.duration)}
                        </div>
                      </div>
                    );
                  },
                },
                {
                  title: '周次',
                  dataIndex: 'weeks',
                  key: 'weeks',
                  width: 120,
                  render: (weeks, record, index) => (
                    <Input
                      value={weeks.join(',')}
                      onChange={(e) => {
                        const newCourses = [...analysisResult.courses];
                        const weekStr = e.target.value;
                        const weekArray = weekStr.split(',').map(w => parseInt(w.trim())).filter(w => !isNaN(w));
                        newCourses[index].weeks = weekArray;
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                      size="small"
                      placeholder="1,2,3,4..."
                    />
                  ),
                },
                {
                  title: '类型',
                  dataIndex: 'type',
                  key: 'type',
                  width: 80,
                  render: (type: string, record, index) => (
                    <Select
                      value={type}
                      onChange={(value) => {
                        const newCourses = [...analysisResult.courses];
                        newCourses[index].type = value as 'required' | 'elective' | 'practice';
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                      size="small"
                      style={{ width: '100%' }}
                    >
                      <Option value="required">必修</Option>
                      <Option value="elective">选修</Option>
                      <Option value="practice">实践</Option>
                    </Select>
                  ),
                },
                {
                  title: '操作',
                  key: 'action',
                  width: 80,
                  render: (_, record, index) => (
                    <Button
                      type="link"
                      danger
                      size="small"
                      onClick={() => {
                        const newCourses = analysisResult.courses.filter((_, i) => i !== index);
                        setAnalysisResult({ ...analysisResult, courses: newCourses });
                      }}
                    >
                      删除
                    </Button>
                  ),
                },
              ]}
              pagination={false}
              size="small"
              scroll={{ x: 1000 }}
            />
          </Card>
          
          <Divider />
          
          <Row gutter={16}>
            <Col span={8}>
              <Button 
                block
                onClick={handleRetry}
                icon={<ReloadOutlined />}
              >
                重新分析
              </Button>
            </Col>
            <Col span={8}>
              <Button 
                block
                onClick={() => setCurrentStep(0)}
                icon={<UploadOutlined />}
              >
                重新上传
              </Button>
            </Col>
            <Col span={8}>
              <Button 
                block
                type="primary" 
                onClick={handleConfirm}
                loading={saving}
                icon={saving ? undefined : <CheckCircleOutlined />}
              >
                {saving ? '正在保存课表...' : '确认生成课表'}
              </Button>
            </Col>
          </Row>
        </div>
      )}
    </Card>
  );
};

export default ScheduleUpload;
